<template>
	<div class="app-container">
		<!-- 搜索 -->
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
			<el-form-item label="客户名称" prop="customerName">
				<el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable style="width: 240px"
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="月结客户" prop="billMonth">
				<el-radio-group v-model="queryParams.billMonth">
					<el-radio v-for="dict in dict.type.sys_costomer_type" :key="dict.value" :label="dict.value">{{
						dict.label }}</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="联系电话" prop="contactPhone">
				<el-input type="tel" maxlength="11" v-model="queryParams.contactPhone" placeholder="请输入联系电话" clearable>
				</el-input>
			</el-form-item>
			<el-form-item label="省/市/区" prop="selectedRegion">
				<el-cascader :options="regionData" v-model="queryParams.selectedRegion" @change="handleRegionChanges"
					placeholder="请选择省/市/区" style="width: 100%;"></el-cascader>
			</el-form-item>
			<el-form-item label="详细地址" prop="address">
				<el-input v-model="queryParams.address" placeholder="请输入详细地址" clearable> </el-input>
			</el-form-item>
			<el-form-item label="账户余额">
				<div style="display: flex;">
					<el-input v-model="queryParams.amountMin" placeholder="请输入最小值" clearable
						@keyup.enter.native="handleQuery" type="number" style="width: 140px;" />
					-
					<el-input v-model="queryParams.amountMax" placeholder="请输入最大值" clearable
						@keyup.enter.native="handleQuery" type="number" style="width: 140px;" />
				</div>
			</el-form-item>
			<el-form-item label="创建时间" prop="dateRange">
				<el-date-picker v-model="queryParams.dateRange" type="daterange" range-separator="至"
					start-placeholder="开始日期" style="width: 240px" value-format="yyyy-MM-dd" end-placeholder="结束日期"
					@change="timeChange">
				</el-date-picker>
			</el-form-item>
			<!-- 防止仅有一个输入框时光标在那一个输入框里时按回车出现“正在加载系统资源，请耐心等待” -->
			<input hidden />

			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<!-- 工具栏 -->
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
					v-hasPermi="['customer:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
					v-hasPermi="['customer:edit']">修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
					@click="handleDelete" v-hasPermi="['customer:remove']">删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
					v-hasPermi="['customer:export']">导出</el-button>
			</el-col>





			<el-col :span="1.5" style="margin-left: 50px;">
				<el-tag>合计金额：{{ amount_sum }}</el-tag>
			</el-col>

			<right-toolbar :showSearch.sync="showSearch" @queryTable="getDataList"></right-toolbar>
		</el-row>

		<!-- 表格 -->
		<el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="ID" prop="id" width="60" />
			<el-table-column label="客户名称" prop="customerName" width="120" show-overflow-tooltip />
			<el-table-column label="账户余额" prop="amount" width="80" show-overflow-tooltip />
			<el-table-column label="月结客户" prop="billMonth" width="80">
				<template slot-scope="scope">
					<dict-tag :options="dict.type.sys_costomer_type" :value="scope.row.billMonth" />
				</template>
			</el-table-column>
			<el-table-column label="联系人" prop="contactPerson" width="120" show-overflow-tooltip />
			<el-table-column label="联系电话" prop="contactPhone" width="120" />
			<el-table-column label="所属省市区" prop="PCA" width="200" />
			<el-table-column label="联系地址" prop="address" show-overflow-tooltip />
			<el-table-column label="创建时间" prop="createTime" width="150" />
			<el-table-column align="center" width="200" class-name="small-padding fixed-width" fixed="right">
				<template slot-scope="scope" v-if="scope.row.roleId !== 1">
					<el-button size="mini" type="text" @click="handleChongzhi(scope.row)"
						v-hasPermi="['customer:pay:add']">账户充值</el-button>
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
						v-hasPermi="['customer:edit']">修改</el-button>
					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
						v-hasPermi="['customer:remove']">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 分页 -->
		<pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize" @pagination="getDataList" />

		<!-- 添加或编辑弹框 -->
		<el-dialog :title="addDialogTitle" :visible.sync="addDialogVisible" width="500px" append-to-body>
			<el-form ref="addFormRef" :model="addDialogFormData" :rules="addDialogFormRules" size="medium"
				label-width="100px">
				<el-form-item label="客户名称" prop="customerName">
					<el-input v-model="addDialogFormData.customerName" placeholder="请输入客户名称" clearable> </el-input>
				</el-form-item>
				<el-form-item label="月结客户" prop="billMonth">
					<el-radio-group v-model="addDialogFormData.billMonth">
						<el-radio v-for="dict in dict.type.sys_costomer_type" :key="dict.value" :label="dict.value">{{
							dict.label }}</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="联系人" prop="contactPerson">
					<el-input v-model="addDialogFormData.contactPerson" placeholder="请输入联系人" clearable> </el-input>
				</el-form-item>
				<el-form-item label="联系电话" prop="contactPhone">
					<el-input type="tel" maxlength="11" v-model="addDialogFormData.contactPhone" placeholder="请输入联系电话"
						clearable> </el-input>
				</el-form-item>
				<el-form-item label="省/市/区" prop="selectedRegion">
					<el-cascader :options="regionData" v-model="addDialogFormData.selectedRegion"
						@change="handleRegionChange" placeholder="请选择省/市/区" style="width: 100%;"></el-cascader>
				</el-form-item>
				<el-form-item label="详细地址" prop="address">
					<el-input v-model="addDialogFormData.address" placeholder="请输入详细地址" clearable> </el-input>
				</el-form-item>
			</el-form>

			<div slot="footer">
				<el-button @click="handleAddDialogCancel">取消</el-button>
				<el-button type="primary" @click="handleAddDialogConfirm">确定</el-button>
			</div>
		</el-dialog>


		<!-- 充值申请 -->
		<el-dialog title="账户充值" :visible.sync="addDialogVisiblepay" width="500px" append-to-body>
			<el-form ref="formpayRef" :model="formpay" :rules="formpayRules" size="medium" label-width="100px">
				<el-form-item label="套餐" prop="packageId">
					<el-select v-model="formpay.packageId" placeholder="请选择">
						<el-option v-for="item in paylist" :key="item.id" :label="item.title" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="收款方式" prop="accountTypeName">
					<el-select v-model="formpay.accountTypeName" placeholder="请选择收款方式" @change="paychang">
						<el-option v-for="item in dict.type.sys_price_type" :key="item.id" :label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="收款账号" prop="accountNumber">
					<el-select v-model="formpay.accountNumber" placeholder="请选择收款账号">
						<el-option v-for="item in zhanghlist" :key="item.id" :label="item.accountNumber"
							:value="item.accountNumber">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="收款日期" prop="datePaymentStr">
					<el-date-picker :clearable="false" :editable="false" value-format="yyyy-MM-dd"
						v-model="formpay.datePaymentStr" type="date" placeholder="选择日期">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="支付凭证" prop="filePayment" style="border: 1px dashed #eee;"
					@paste.native="handlePaste">
					<div style="color: red;">点击虚线区域可粘贴上传</div>
					<el-upload list-type="picture-card" :file-list="fileList" ref="productImage" :action="uploadAction"
						:headers="uploadHeaders" :on-success="handleUploadSuccess" multiple>
						<i class="el-icon-plus"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input v-model="formpay.remark" placeholder="请输入联系人" clearable> </el-input>
				</el-form-item>
			</el-form>

			<div slot="footer">
				<el-button @click="handleAddDialogCancel">取消</el-button>
				<el-button type="primary" @click="payConfirm">申请充值</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
// 客户管理

import {
	postCustomerList,
	postCustomerInfo,
	postCustomerAdd,
	postCustomerEdit,
	postCustomerRemove,
	payAdd,
	getList,
	getzhanghList,
	getSum
} from '@/api/customer'
import {
	validMobile
} from '@/utils/validate'
import {
	regionData,
	codeToText,
	pcaTextArr
} from 'element-china-area-data'
import { getToken } from '@/utils/auth'
export default {
	name: 'CustomerList',
	dicts: [
		"sys_costomer_type", "sys_price_type"
	],
	data() {
		// 验证手机号码
		const validateMobile = (rule, value, callback) => {
			if (!validMobile(value)) {
				callback(new Error('请输入正确的手机号码'))
			} else {
				callback()
			}
		}
		return {
			// 必选参数，上传的地址
			uploadAction: process.env.VUE_APP_BASE_API + '/common/upload',
			// 设置上传的请求头部
			uploadHeaders: {
				Authorization: 'Bearer ' + getToken()
			},
			// 上传的文件列表
			uploadImageList: [],
			regionData: pcaTextArr,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				customerName: undefined,
				billMonth: undefined,
				contactPhone: undefined,
				selectedRegion: undefined,
				address: undefined,
				province: undefined,
				city: undefined,
				county: undefined,
				daterange: [],
				beginTime: undefined,
				endTime: undefined,
				amountMin: '',
				amountMax: '',
			},
			// 数据列表
			dataList: [],
			// 生产角色下所有用户列表
			scUserList: [],
			// 添加弹框标题
			addDialogTitle: '',
			// 添加弹框是否显示
			addDialogVisible: false,
			addDialogVisiblepay: false,

			// 添加弹框表单参数
			addDialogFormData: {
				billMonth: '否',
				selectedRegion: []
			},
			// 添加弹框表单校验
			addDialogFormRules: {
				customerName: [{
					required: true,
					message: '请输入客户名称',
					trigger: 'blur'
				}],
				billMonth: [{
					required: true,
					message: '请选择是否为月结客户',
					trigger: 'blur'
				}],
				contactPerson: [{
					required: true,
					message: '请输入联系人',
					trigger: 'blur'
				}],
				contactPhone: [{
					required: true,
					message: '请输入联系电话',
					trigger: 'blur'
				},
				{
					validator: validateMobile,
					trigger: 'blur'
				},
				],


				selectedRegion: [{
					required: true,
					message: '请选择省市区',
					trigger: 'blur'
				}],
				province: [{
					required: true,
					message: '请输入省',
					trigger: 'blur'
				}],
				city: [{
					required: true,
					message: '请输入市',
					trigger: 'blur'
				}],
				county: [{
					required: true,
					message: '请输入区/县',
					trigger: 'blur'
				}],
				address: [{
					required: true,
					message: '请输入详细地址',
					trigger: 'blur'
				}],
			},
			isshow: false,
			formpay: {
				customerId: 0,
				packageId: '',
				accountNumber: '',
				datePaymentStr: ''
			},
			formpayRules: {
				packageId: [{ required: true, message: '请选择套餐', trigger: 'blur' }],
				accountTypeName: [{ required: true, message: '请选择收款方式', trigger: 'blur' }],
				accountNumber: [{ required: true, message: '收款账号不能为空', trigger: 'blur' }],
				datePaymentStr: [{ required: true, message: '选择收款日期', trigger: 'blur' }],
				filePayment: [{ required: true, message: '支付凭证不能为空', trigger: 'blur' }],
			},
			paylist: [],
			zhanghlist: [],//收款账号下拉
			fileList: [],
			amount_sum: 0
		}
	},
	created() {
		this.getDataList()
		getSum({}).then(res => {
			this.amount_sum = res.data.amount_sum
		})
	},
	methods: {
		/** 导出按钮操作 */
		handleExport() {
			this.download(
				"customer/export",
				{
					...this.queryParams,
				},
				`客户信息.xlsx`
			);
		},
		timeChange(e) {
			if (e != null) {
				this.queryParams.beginTime = e[0]
				this.queryParams.endTime = e[1]
			} else {
				this.queryParams.beginTime = undefined
				this.queryParams.endTime = undefined
			}

		},
		handleRegionChanges(value) {
			this.queryParams.province = value[0]
			this.queryParams.city = value[1]
			this.queryParams.county = value[2]
		},
		setDate() {
			let currentDate = new Date();
			let year = currentDate.getFullYear();
			let month = String(currentDate.getMonth() + 1).padStart(2, '0');
			let day = String(currentDate.getDate()).padStart(2, '0');
			this.formpay.datePaymentStr = `${year}-${month}-${day}`
		},
		handleRegionChange(value) {
			this.addDialogFormData.selectedRegion = [value[0], value[1], value[2]]
			// 当选择发生变化时，处理省市区的变更逻辑
			this.addDialogFormData.province = value[0]
			this.addDialogFormData.city = value[1]
			this.addDialogFormData.county = value[2]
		},
		/** 查询列表 */
		getDataList() {
			this.loading = true
			postCustomerList(this.queryParams).then((response) => {
				response.rows.forEach((item) => {
					item.PCA = `${item.province} ${item.city} ${item.county}`
				})
				this.dataList = response.rows
				this.total = response.total
				this.loading = false
			})
		},  // 表单重置
		reset() {
			this.addDialogFormData = {
				id: "",
				billMonth: "否",
				selectedRegion: []
			};
			this.resetForm("addFormRef");
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.getDataList()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.queryParams.dateRange = []
			this.queryParams.selectedRegion = []
			this.queryParams.province = undefined
			this.queryParams.city = undefined
			this.queryParams.county = undefined
			this.queryParams.beginTime = undefined
			this.queryParams.endTime = undefined

			this.resetForm('queryForm')
			this.handleQuery()
		},
		/** 多选框选中数据 */
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.id)
			this.single = selection.length != 1
			this.multiple = !selection.length
		},
		handleAddDialogCancel() {
			this.addDialogVisible = false
			this.addDialogVisiblepay = false

		},
		/** 删除按钮操作 */
		handleDelete(row) {
			let userIds = row.id || this.ids;
			if (typeof userIds == "number") {
				userIds = [userIds];
			}
			this.$modal
				.confirm('是否确认删除ID为"' + userIds + '"的数据项？')
				.then(function () {
					return postCustomerRemove({ ids: userIds });
				})
				.then(() => {
					this.getDataList();
					this.$modal.msgSuccess("删除成功");
				})
				.catch(() => { });
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset()
			this.isshow = false;
			this.addDialogVisible = true
			this.addDialogTitle = '添加客户'
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset();
			postCustomerInfo({ id: row.id }).then((response) => {
				this.addDialogFormData = response.data;
				this.isshow = true;
				this.addDialogVisible = true;
				this.title = "修改客户";
				this.addDialogFormData.selectedRegion = [this.addDialogFormData.province, this.addDialogFormData.city, this.addDialogFormData.county]
			});
		},

		/** 提交按钮 */
		handleAddDialogConfirm: function () {
			console.log(this.addDialogFormData);
			this.$refs["addFormRef"].validate((valid) => {
				if (valid) {
					if (this.isshow) {
						postCustomerEdit(this.addDialogFormData).then((response) => {
							this.$modal.msgSuccess("修改成功");
							this.addDialogVisible = false;
							this.getDataList();
						});
					} else {
						postCustomerAdd(this.addDialogFormData).then((response) => {
							this.$modal.msgSuccess("新增成功");
							this.addDialogVisible = false;
							this.getDataList();
						});
					}
				}
			});
		},

		handleChongzhi(row) {
			this.formpay.customerId = row.id
			getList({ pageNum: 1, pageSize: 1000 }).then(res => {
				this.paylist = res.rows
			})
			this.setDate()
			this.addDialogVisiblepay = true
		},
		paychang(e) {
			this.formpay.accountNumber = ''
			getzhanghList({ pageNum: 1, pageSize: 1000, accountType: e }).then(res => {
				this.zhanghlist = res.rows
			})
		},
		// 上传图片
		handleUploadSuccess(response, file, fileList) {
			this.formpay.filePayment = fileList.map(item => item.response.url)
		},
		handlePaste(e) {
			let now = new Date().getTime()
			if (now - this.timeStep < 500) {
				this.$message.warning('粘贴速度太频繁！请稍后再试');
				return
			}
			this.timeStep = now
			var clipboardData = e.clipboardData; // IE
			if (!clipboardData) {
				//chrome
				clipboardData = e.originalEvent.clipboardData;
			}
			var items = '';
			items = (e.clipboardData || window.clipboardData).items;
			let file = null;
			if (!items || items.length === 0) {
				this.$message.error('当前浏览器不支持粘贴本地图片，请打开图片复制后再粘贴！');
				return;
			}
			// 搜索剪切板items
			for (let i = 0; i < items.length; i++) {
				// 限制上传文件类型
				if (items[i].type.indexOf('image') !== -1) {
					file = items[i].getAsFile();
					break;
				}
			}
			if (file) {
				this.$refs.productImage.handleStart(file); // 将粘贴过来的图片加入预上传队列
				this.$refs.productImage.submit(); // 提交图片上传队列
			} else {
				this.$message.error("粘贴内容非图片");
			}
		},
		payConfirm: function () {
			console.log(this.formpay);
			this.$refs["formpayRef"].validate((valid) => {
				if (valid) {
					this.formpay.filePayment = this.formpay.filePayment.toString()
					payAdd(this.formpay).then((response) => {
						this.$modal.msgSuccess("已申请，审核通过可到账");
						this.addDialogVisiblepay = false;
						this.getDataList();
					});

				}
			});
		},
	},
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}

.avatar-uploader .el-upload:hover {
	border-color: #409EFF;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}

.avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>